package myThread;

class MyBlockingQueue{
    private String[] data = null;

    //队首
    private int head = 0;
    //队尾
    private int tail = 0;
    //元素个数
    private int size = 0;
    public MyBlockingQueue(int capacity){
        data = new String[capacity];
    }
    public void put(String elem) throws InterruptedException {
        synchronized (this){
            while (size>=data.length){
                //满了,阻塞
                this.wait();
            }
            data[tail++] = elem;
            if(tail>=data.length){
                tail = 0;
            }
            size++;
            this.notify();//通知消费者线程,此时线程不空,可以继续消费了
        }

    }
    public String take() throws InterruptedException {
        synchronized (this){
        while (size == 0){
            //为空,阻塞
            this.wait();
        }
        String ret = data[head++];
        if(head>=data.length){
            head = 0;
        }
        size--;
        this.notify();//通知生产者线程,线程此时不为满,可以生产元素
        return ret;
        }
    }
}
public class demo30 {
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue(1000);
        Thread prodcer = new Thread(()->{
            int n = 0;
            while(true){
                try {
                    queue.put(n+"");
                    System.out.println("生产元素" +n);
                    n++;
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread consumer = new Thread(()->{
            while(true){
                try {
                    String tmp = queue.take();
                    System.out.println("消费元素"+tmp);
                    //Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        prodcer.start();
        consumer.start();
    }
}
